import { reactive } from 'vue'

import { format } from 'date-fns'
import { parseTime } from '@/common/common'
import { UserInfo } from '@/service/modules/user/types'
import { getProUserListReq } from '@/service/modules/user'
import { delProMenberReq } from '@/service/modules/project'

export function useTable() {
  const state = reactive({
    page: 1,
    limit: 10,
    count: 0,
    proId: 0,
    list: [],
    loading: false,
    currentRecord: {} as UserInfo,
    userDetailModalShow: false,
    modProRolesModalShow: false
  })

  const getList = async () => {
    if (state.loading) return
    state.loading = true

    const { data, count } = await getProUserListReq({
      page: state.page,
      limit: state.limit,
      proId: state.proId
    })
    state.loading = false
    if (!data) throw Error()
    state.list = data.map((record: UserInfo) => {
      record.createTime = record.createTime
        ? format(parseTime(record.createTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      record.updateTime = record.updateTime
        ? format(parseTime(record.updateTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      return record
    })
    state.count = count
  }

  const delProMenber = async (userId: number, username: string) => {
    window.$dialog.warning({
      title: window.$t('dialog.warningTitle'),
      content: window.$t('project.delProMenberTips') + username,
      positiveText: window.$t('dialog.positiveText'),
      negativeText: window.$t('dialog.negativeText'),
      onPositiveClick: async () => {
        const res = await delProMenberReq({ userId: userId })
        if (res.resp_code === 0) {
          updateList()
        }
      }
    })
  }

  const updateList = () => {
    if (state.list.length === 1 && state.page > 1) {
      --state.page
    }
    getList()
  }

  const onOperationClick = (
    data: { rowData: UserInfo },
    type: 'modProRoles' | 'showUserDetail' | 'delProMenber'
  ) => {
    state.currentRecord = data.rowData
    switch (type) {
      case 'modProRoles':
        state.modProRolesModalShow = true
        break
      case 'showUserDetail':
        state.userDetailModalShow = true
        break
      case 'delProMenber':
        delProMenber(data.rowData.id, data.rowData.username)
        break
    }
  }

  const changePage = (page: number) => {
    state.page = page
    getList()
  }

  const changePageSize = (limit: number) => {
    state.page = 1
    state.limit = limit
    getList()
  }

  // onMounted(() => {
  //   getList()
  // })

  return {
    state,
    changePage,
    changePageSize,
    updateList,
    onOperationClick
  }
}
